﻿using Common.DictComponent;
using DAL;
using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.EntityFrameworkCore;
using Model;
using NPOI.SS.Formula.Functions;
using Service;
using System.Data;
using System.Threading.Tasks;
using WMS.Models;
using static NPOI.HSSF.UserModel.HeaderFooter;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WMS.Controllers
{
    public class BiProductController : Controller
    {
        /// <summary>
        /// 货品信息
        /// </summary>
        private readonly IBiProductService _ibps;
        /// <summary>
        /// 供应商
        /// </summary>
        private readonly IBiSupplierService _ibss;
        /// <summary>
        /// 客户
        /// </summary>
        private readonly IBiCustomerService _ibcs;
        /// <summary>
        /// 货品类型
        /// </summary>
        private readonly IGoodsTypeService _igts;
        /// <summary>
        /// 仓库
        /// </summary>
        private readonly IBiWarehouseService _ibws;
        /// <summary>
        /// 批次
        /// </summary>
        private readonly IWhBatchService _iwbs;
        /// <summary>
        /// 库存
        /// </summary>
        private readonly IWhInventoryService _iwis;
        /// <summary>
        /// 库位
        /// </summary>
        private readonly IWhLocationService _iwls;
        /// <summary>
        /// 数据字典
        /// </summary>
        private readonly IDictService _ids;
        /// <summary>
        /// 销售订单
        /// </summary>
        private readonly IOmSalesOrderService _iosos;
        /// <summary>
        /// 编号规则
        /// </summary>
        private readonly INumberingRuleService _inbrs;
        private readonly AppDbContext _context;

        public BiProductController(
            IBiProductService ibps,
            IGoodsTypeService igts,
            IBiSupplierService ibss,
            IBiCustomerService ibcs,
            IBiWarehouseService ibws,
            IWhBatchService iwbs,
            IWhInventoryService iwis,
            IWhLocationService iwls,
            IDictService ids,
            IOmSalesOrderService iosos,
            AppDbContext context,
            INumberingRuleService inbrs
            )
        {
            _ibps = ibps;
            _igts = igts;
            _ibss = ibss;
            _ibcs = ibcs;
            _ibws = ibws;
            _iwbs = iwbs;
            _iwis = iwis;
            _iwls = iwls;
            _ids = ids;
            _iosos = iosos;
            _context = context;
            _inbrs = inbrs;
        }
        /// <summary>
        /// 货品主页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 初始数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var result = _ibps.GetAllWithDetailsAsync();

            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "错误" });
            }
        }
        /// <summary>
        /// 货品详细信息页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Details(int id, string pwd)
        {
            return View();
        }
        /// <summary>
        /// 详细信息请求
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Details(int id)
        {
            var result = await _ibps.GetAllWithDetailsIdAsync(id);
            if (result != null)
            {
                return Ok(new { code = 300, data = result, msg = "查询成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "错误" });
            }
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加提交
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] BiProductCreateModel model)
        {
            string number = await _inbrs.GenerateAndUpdateNumberAsync(1);
            // 使用事务确保数据一致性
            using var transaction = await _context.Database.BeginTransactionAsync();
            try
            {
                model.Product.GoodsCode = number;
                // 创建货品
                var product = model.Product;
                var result = await _ibps.CreateAsync(product);
                if (result <= 0)
                {
                    await transaction.RollbackAsync();
                    return Ok(new { code = 500, msg = "货品创建失败" });
                }
/*
                // 创建库位库存
                if (model.InventoryList != null && model.InventoryList.Any())
                {
                    foreach (var inventory in model.InventoryList)
                    {
                        if (inventory.InitialStock <= 0)
                        {
                            await transaction.RollbackAsync();
                            return Ok(new { code = 400, msg = $"库位ID：{inventory.StoraqeLocationId} 期初库存必须大于0" });
                        }

                        // 计算单价（总金额 ÷ 总库存）
                        var unitPrice = inventory.InitialStock > 0 ? inventory.InitialAmount / inventory.InitialStock : 0;

                        // 创建库存记录 - 直接关联库位
                        var whInventory = new WhInventory
                        {
                            WarehouseId = inventory.WarehouseId,
                            StoraqeLocationId = inventory.StoraqeLocationId, // 新增库位ID
                            GoodsId = product.GoodsId,
                            UnitPrice = unitPrice,
                            AvailableInventoryQty = inventory.InitialStock,  // 使用期初库存数量
                            TotalPlannedQuantity = inventory.InitialStock,   // 使用期初库存数量
                            StockUpperLimit = inventory.StockUpperLimit,
                            StockLowerLimit = inventory.StockLowerLimit,
                        };

                        await _iwis.CreateAsync(whInventory);

                        // 同时更新库位详情表
                        var locationDetail = new WhLocationDetail
                        {
                            StorageLocationId = inventory.LocationId,
                            GoodsId = product.GoodsId,
                            AvailableInventoryQuantity = inventory.InitialStock,
                            InboundTotal = inventory.InitialStock,
                            TotalPlannedQuantity = inventory.InitialStock,
                            CreateBy = product.CreateBy,
                            UpdateBy = product.UpdateBy,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Remark = inventory.Remark,
                        };

                        await _iwlds.CreateAsync(locationDetail);
                    }
                }*/

                await transaction.CommitAsync();
                return Ok(new { code = 200, data = new { goodsId = product.GoodsId }, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                return Ok(new { code = 500, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取仓库及库位的方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllWithLocations()
        {
            var result = await _ibps.GetAllWithLocationsAsync();
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "获取失败" });
            }
        }

        /// <summary>
        /// 修改页面 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(int id)
        {
            return View();
        }

        /// <summary>
        /// 修改提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(int id, BiProduct date)
        {
            var result = await _ibps.UpdateAsync(date);
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "更新成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "未知错误导致未更新成功" });
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            var result = await _ibps.DeleteAsync(id);
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "删除成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "未知错误导致未删除成功" });
            }
        }
        /// <summary>
        /// 查询该货品的库存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetInventoryByGoodsId(long id)
        {
            var result = await _ibps.GetInventoryByGoodsId(id);
            if (result != null)
            {
                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "未知错误导致未获取成功" });
            }
        }

        /// <summary>
        /// 获取货品类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ProductTypeAllync()
        {
            List<GoodsType> type = await _igts.GoodsTypesAllAsync();
            if (type == null)
            {
                return Ok(new { code = 404, msg = "加载失败" });
            }
            else
            {
                var date = type.Select(T => new
                {
                    Id = T.GoodsTypeId,
                    Name = T.GoodsTypeName,
                    FId = T.ParentCategoryId
                }).ToList();
                if (date != null)
                {
                    return Ok(new { code = 200, data = date, msg = "获取成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "出现错误，请检查" });
                }
            }
        }
        /// <summary>
        /// 客户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CustomerAll()
        {
            var data = await _ibcs.GetAllAsync();
            var dateyl = data.Select(T => new
            {
                Id = T.CustomerId,
                Name = T.CustomerName
            }).ToList();
            if (dateyl != null)
            {
                return Ok(new { code = 200, data = dateyl, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "出现错误，请检查" });
            }
        }
        /// <summary>
        /// 供应商信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SupplierAll()
        {
            var data = await _ibss.GetAllAsync();
            var dateyl = data.Select(T => new
            {
                Id = T.SupplierId,
                Name = T.SupplierName
            }).ToList();
            if (dateyl != null)
            {
                return Ok(new { code = 200, data = dateyl, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "出现错误，请检查" });
            }
        }
        /// <summary>
        /// 获取仓库
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> WhAll()
        {
            var date = await _ibws.GetAllAsync();
            if (date != null)
            {
                return Ok(new { code = 200, data = date, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "出现错误，请检查" });
            }
        }
        /// <summary>
        /// 获取数据字典数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> DictDate()
        {
            // 调用公共组件方法获取性别字典数据
            var dictType = await _ids.GetDictTypeAsync("sys_normal_statu");
            if (dictType != null)
            {
                var dict = await _ids.GetDictDataListAsync(dictType.DictTypeId);
                var date = dict.Select(t => new
                {
                    Id = t.DictDataId,
                    Name = t.Name
                });
                return Ok(new { code = 200, data = date, msg = "获取成功" });
            }
            else
            {
                return Ok(new { code = 404, msg = "获取失败" });
            }
        }
        /// <summary>
        /// 状态变更（启用停用）
        /// </summary>
        /// <param name="status">字符串类型的状态参数如0,1</param>
        /// <param name="id">目标订单</param>
        /// <returns></returns>
        public async Task<IActionResult> Status(string status, long id)
        {
            if(status!="0" || status != "1")
            {
            }
            if (await _ibps.Status(status, id) > 0)
            {
                return this.Success("状态变更成功");
            }
            else
            {
                return this.Error();
            }
        }
        public class BiProductCreateModel
        {
            public BiProduct Product { get; set; }
            public List<InventoryCreateModel> InventoryList { get; set; }
        }

        public class InventoryCreateModel
        {
            public long WarehouseId { get; set; }
            public long StoraqeLocationId { get; set; }
            public decimal InitialStock { get; set; }

            public decimal InitialAmount { get; set; }

            public decimal StockUpperLimit { get; set; }

            public decimal StockLowerLimit { get; set; }

            public string Remark { get; set; }
            public List<BatchCreateModel> InitialStockBatches { get; set; }
        }

        public class BatchCreateModel
        {
            public decimal Quantity { get; set; }

            // 允许数字自动转换为字符串
            public string BatchNo { get; set; }

            public string ProductionDate { get; set; }
        }
        // 添加所需的DTO类
        public class WarehouseWithLocationsDTO
        {
            public long WarehouseId { get; set; }
            public string WarehouseCode { get; set; }
            public string WarehouseName { get; set; }
            public string WarehouseAddress { get; set; }
            public decimal WarehouseCapacity { get; set; }
            public List<LocationDTO> Locations { get; set; }
        }

        public class LocationDTO
        {
            public long StorageLocationId { get; set; }
            public string StorageLocationCode { get; set; }
            public string storageLocationName { get; set; }
            public decimal storageLcationCapacity { get; set; }
        }
    }
}
